// AI绘图API服务
import { ElMessage } from 'element-plus'

// 后端API基础URL
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:3001';

// 生成头像图片
export const generateAvatarImage = async (settings) => {
  try {
    // 调用后端API生成头像
    const response = await fetch(`${API_BASE_URL}/api/avatar/generate`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        type: settings.type || 'engineer',
        gender: settings.gender || 'male',
        expression: settings.expression || 'normal',
        age: settings.age || 35,
        customDescription: settings.customDescription || '',
        personality: settings.personality || ['严谨专业']
      })
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const result = await response.json();
    
    if (result.success) {
      // 处理后端返回的数据结构
      const data = result.data;
      
      // 如果后端返回的是相对路径，转换为完整URL
      if (data.imageUrl && data.imageUrl.startsWith('/')) {
        data.imageUrl = `${API_BASE_URL}${data.imageUrl}`;
      }
      
      // 直接返回后端的数据，添加success标志
      return {
        success: true,
        ...data
      };
    } else {
      throw new Error(result.message || '头像生成失败');
    }
  } catch (error) {
    console.error('调用后端API失败:', error);
    ElMessage.error('AI绘图生成失败，请稍后重试');
    
    // 如果后端API失败，回退到模拟数据
    return await mockAIGeneration(settings);
  }
};

// 模拟AI生成过程（作为备用方案）
const mockAIGeneration = async (description) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      // 根据描述生成不同的模拟图片URL
      const imageUrl = generateMockImageUrl(description);
      resolve({
        imageUrl,
        description: description.customDescription || generateDescription(description),
        settings: description,
        generatedAt: new Date().toISOString()
      });
    }, 2000); // 模拟2秒生成时间
  });
};

// 根据描述生成模拟图片URL
const generateMockImageUrl = (description) => {
  // 这里可以根据描述返回不同的模拟图片
  // 实际项目中应该调用真实的AI绘图API
  const baseUrl = 'https://api.dicebear.com/7.x/avataaars/svg';
  const params = new URLSearchParams({
    seed: description.type + '-' + description.gender,
    backgroundColor: 'b6e3f4',
    radius: '50',
    style: 'circle',
    width: '180',
    height: '280'
  });
  
  return `${baseUrl}?${params.toString()}`;
};

// 获取预设的形象模板
export const getAvatarTemplates = async () => {
  try {
    // 尝试从后端获取模板
    const response = await fetch(`${API_BASE_URL}/api/avatar/templates`);
    if (response.ok) {
      const result = await response.json();
      if (result.success) {
        // 如果后端返回的是相对路径，转换为完整URL
        result.data.forEach(template => {
          if (template.imageUrl && template.imageUrl.startsWith('/uploads/')) {
            template.imageUrl = `${API_BASE_URL}${template.imageUrl}`;
          }
        });
        return result.data;
      }
    }
  } catch (error) {
    console.error('获取后端模板失败，使用本地模板:', error);
  }
  
  // 如果后端失败，返回本地模板
  return [
    {
      id: 'engineer-male',
      name: '资深工程师',
      gender: 'male',
      description: '一位经验丰富的男性工程师，穿着蓝色工作服和安全帽，手持图纸，站在工程现场，表情严肃认真，年龄约45岁，全身像',
      imageUrl: 'https://api.dicebear.com/7.x/avataaars/svg?seed=engineer-male&backgroundColor=b6e3f4&radius=50&style=circle&width=180&height=280'
    },
    {
      id: 'engineer-female',
      name: '资深工程师',
      gender: 'female',
      description: '一位经验丰富的女性工程师，穿着白色工作服和安全帽，手持平板电脑，站在设计办公室，表情专注，年龄约40岁，全身像',
      imageUrl: 'https://api.dicebear.com/7.x/avataaars/svg?seed=engineer-female&backgroundColor=b6e3f4&radius=50&style=circle&width=180&height=280'
    },
    {
      id: 'technician-male',
      name: '年轻技术员',
      gender: 'male',
      description: '一位年轻的男性技术员，穿着橙色工作服，手持工具，站在设备旁，表情友好，年龄约28岁，全身像',
      imageUrl: 'https://api.dicebear.com/7.x/avataaars/svg?seed=technician-male&backgroundColor=b6e3f4&radius=50&style=circle&width=180&height=280'
    },
    {
      id: 'technician-female',
      name: '年轻技术员',
      gender: 'female',
      description: '一位年轻的女性技术员，穿着绿色工作服，手持测量仪器，站在施工现场，表情积极，年龄约26岁，全身像',
      imageUrl: 'https://api.dicebear.com/7.x/avataaars/svg?seed=technician-female&backgroundColor=b6e3f4&radius=50&style=circle&width=180&height=280'
    },
    {
      id: 'architect-male',
      name: '建筑师',
      gender: 'male',
      description: '一位专业的男性建筑师，穿着深色西装，手持建筑模型，站在设计工作室，表情自信，年龄约35岁，全身像',
      imageUrl: 'https://api.dicebear.com/7.x/avataaars/svg?seed=architect-male&backgroundColor=b6e3f4&radius=50&style=circle&width=180&height=280'
    },
    {
      id: 'architect-female',
      name: '建筑师',
      gender: 'female',
      description: '一位专业的女性建筑师，穿着灰色套装，手持设计图纸，站在现代办公室，表情优雅，年龄约32岁，全身像',
      imageUrl: 'https://api.dicebear.com/7.x/avataaars/svg?seed=architect-female&backgroundColor=b6e3f4&radius=50&style=circle&width=180&height=280'
    },
    {
      id: 'consultant-male',
      name: '专业顾问',
      gender: 'male',
      description: '一位资深的男性顾问，穿着深蓝色西装，手持文件夹，站在会议室，表情睿智，年龄约50岁，全身像',
      imageUrl: 'https://api.dicebear.com/7.x/avataaars/svg?seed=consultant-male&backgroundColor=b6e3f4&radius=50&style=circle&width=180&height=280'
    },
    {
      id: 'consultant-female',
      name: '专业顾问',
      gender: 'female',
      description: '一位资深的女性顾问，穿着黑色职业装，手持笔记本电脑，站在办公桌前，表情专业，年龄约45岁，全身像',
      imageUrl: 'https://api.dicebear.com/7.x/avataaars/svg?seed=consultant-female&backgroundColor=b6e3f4&radius=50&style=circle&width=180&height=280'
    }
  ];
};

// 根据设置获取对应的模板
export const getAvatarTemplate = async (type, gender) => {
  try {
    // 尝试从后端获取特定模板
    const response = await fetch(`${API_BASE_URL}/api/avatar/templates/${type}/${gender}`);
    if (response.ok) {
      const result = await response.json();
      if (result.success) {
        // 如果后端返回的是相对路径，转换为完整URL
        if (result.data.imageUrl && result.data.imageUrl.startsWith('/uploads/')) {
          result.data.imageUrl = `${API_BASE_URL}${result.data.imageUrl}`;
        }
        return result.data;
      }
    }
  } catch (error) {
    console.error('获取后端特定模板失败，使用本地模板:', error);
  }
  
  // 如果后端失败，返回本地模板
  const templates = await getAvatarTemplates();
  return templates.find(t => t.id === `${type}-${gender}`) || templates[0];
};

// 生成自定义描述
export const generateDescription = (settings) => {
  const { type, gender, expression, age = 35 } = settings;
  
  const professions = {
    engineer: '资深工程师',
    technician: '年轻技术员',
    architect: '建筑师',
    consultant: '专业顾问'
  };
  
  const genders = {
    male: '男性',
    female: '女性',
    neutral: '中性'
  };
  
  const expressions = {
    normal: '表情自然',
    thinking: '表情专注思考',
    explaining: '表情热情讲解',
    smiling: '表情友善微笑',
    serious: '表情严肃认真',
    happy: '表情轻松愉快'
  };
  
  const outfits = {
    engineer: {
      male: '穿着蓝色工作服和安全帽',
      female: '穿着白色工作服和安全帽'
    },
    technician: {
      male: '穿着橙色工作服',
      female: '穿着绿色工作服'
    },
    architect: {
      male: '穿着深色西装',
      female: '穿着灰色套装'
    },
    consultant: {
      male: '穿着深蓝色西装',
      female: '穿着黑色职业装'
    }
  };
  
  const accessories = {
    engineer: '手持图纸',
    technician: '手持工具',
    architect: '手持建筑模型',
    consultant: '手持文件夹'
  };
  
  const locations = {
    engineer: '站在工程现场',
    technician: '站在设备旁',
    architect: '站在设计工作室',
    consultant: '站在会议室'
  };
  
  const outfit = outfits[type]?.[gender] || '穿着专业的工作服装';
  const accessory = accessories[type] || '';
  const location = locations[type] || '';
  
  return `一位${professions[type]}，${genders[gender]}，${outfit}，${accessory}，${location}，${expressions[expression]}，年龄约${age}岁，全身像`;
}; 